package cc.admin.common.db.table.reader;

import cc.admin.common.db.table.base.EtlReader;
import cc.admin.common.db.table.entity.MetaSql;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
/**
 * @author: ZhangHouYing
 * @date: 2018-06-24
 */
@Slf4j
public class MysqlReader extends EtlReader {

	/**
	 * table_name
	 */
	private String tableSql = "select  table_name,table_comment from information_schema.tables ";
	/**
	 * table_name ,comments
	 */
	private String tableCommentSql = "select  table_name,table_comment comments from information_schema.tables ";
	/**
	 * 对于oracle来说number类型 有效位数为 data_precision  不是data_length
	 * table_name,column_name,data_type,data_length,data_precision,data_scale,nullable
	 */
	private String columnSql = "select table_name,column_name, column_comment, upper(data_type) as data_type, IFNULL(character_maximum_length,0) data_length,numeric_precision data_precision,numeric_scale data_scale,is_nullable nullable from information_schema.columns";
	/**
	 * table_name,column_name,comments
	 */
	private String columnCommentSql = "select table_name,column_name,column_comment comments from information_schema.columns";
	/**
	 * table_name,column_name
	 */
	private String pkSql = "select  table_name,column_name from  information_schema.key_column_usage where CONSTRAINT_NAME='PRIMARY'";

	public MysqlReader() {
	}

	@Override
	protected String getDbNameSql() {
		return "select database()";
	}

	/**
	 * 获取某个用户下指定表结构
	 */
	@Override
	public void initAllSql() {
		if (StrUtil.isNotEmpty(owner)) {
			this.tableSql += " where table_schema = '" + owner + "'  and table_type='BASE TABLE'";
			this.tableCommentSql += " where table_schema = '" + owner + "'";
			this.columnSql += " where table_schema = '" + owner + "'";
			this.columnCommentSql += " where table_schema = '" + owner + "'";
			this.pkSql += " and table_schema = '" + owner + "'";
			if (StrUtil.isNotEmpty(tableName)) {
				this.tableSql += " and  table_name='" + tableName + "'";
				this.tableCommentSql += " and table_name='" + tableName + "'";
				this.columnSql += " and table_name='" + tableName + "'";
				this.columnCommentSql += " and table_name='" + tableName + "'";
				this.pkSql += " and table_name='" + tableName + "'";
			}
		}
		this.columnSql += " order by ordinal_position ";
		this.metaSql = new MetaSql(tableSql, tableCommentSql, columnSql, columnCommentSql, pkSql);
	}

	@Override
	public String getPageDataSql(String sql, int pageNo, int pageSize) {
		return String.format("%s limit %d, %d", sql, (pageNo - 1) * pageSize, pageSize);
	}
}
